package com.chat.common.common.interceptor;

import cn.hutool.core.collection.CollectionUtil;
import com.chat.common.common.domain.dto.RequestInfo;
import com.chat.common.common.exception.HttpErrorEnum;
import com.chat.common.common.utils.RequestHolder;
import com.chat.common.user.domain.enums.BlackTypeEnum;
import com.chat.common.user.service.cache.UserCache;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

@Component
public class BlackInterceptor implements HandlerInterceptor {

    @Resource
    private UserCache userCache;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取拉黑的全部名单 and 我们使用缓存获取的这些名单 然后将这个用户拉黑以后 要清空缓存
        Map<Integer, Set<String>> blackMap = userCache.getBlackMap();

        RequestInfo info = RequestHolder.get();
        if(isBlackList(info.getIp(),blackMap.get(BlackTypeEnum.IP.getId()))){
            HttpErrorEnum.ACCESS_DENIED.sendHttpError(response);
            return false;
        }
        if(isBlackList(info.getUid(),blackMap.get(BlackTypeEnum.UID.getId()))){
            HttpErrorEnum.ACCESS_DENIED.sendHttpError(response);
            return false;
        }

        return true;
    }

    private boolean isBlackList(Object target, Set<String> set) {
        if(Objects.isNull(target)|| CollectionUtil.isEmpty(set)){
            return false;
        }
        return set.contains(target.toString());

    }
}
